package be.bejug.setris.swingtools

import javax.swing.SwingUtilities
import java.awt.event.{KeyListener, KeyAdapter, KeyEvent, ActionListener, ActionEvent, MouseListener, MouseAdapter, MouseEvent}

/**
 * User: Peter
 * Date: 29-mei-2010
 * Time: 8:56:31
 */

object	SwingTools {

	implicit def funToKeyTypedListener(fun:KeyEvent=>Unit):KeyListener = {
		new KeyAdapter{
			override def keyTyped(e: KeyEvent): Unit = fun(e)
		}
	}

	implicit def	funToActionListener(fun:ActionEvent=>Unit):ActionListener = {
		new ActionListener{
			def actionPerformed(e: ActionEvent): Unit = {
				fun(e);
			}
		}
	}
	implicit def funToActionListener2(fun: => Unit):ActionListener = {
		new ActionListener{
			def actionPerformed(e: ActionEvent): Unit = {
				fun
			}
		}
	}
	implicit def	funToRunnable(fun: => Unit):Runnable = {
		new Runnable() {
			def	run {
				fun;
			}
		}
	}

	def	swingRunAndWait(fun: => Unit):Unit = {
		if(SwingUtilities.isEventDispatchThread){
			fun
		} else {
			SwingUtilities.invokeAndWait(new Runnable() {
				def run: Unit = {
					fun
				}
			})
		}
	}

	def	swingRunLater(fun: => Unit){
		if(SwingUtilities.isEventDispatchThread){
			fun
		} else {
			SwingUtilities.invokeLater(new Runnable() {
				def run: Unit = {
					try {
						fun
					} catch {
						case e:Exception => e.printStackTrace()
					}
				}
			})
		}
	}

	def	mouseClicked(fun: MouseEvent => Unit):MouseListener = {
		new MouseAdapter() {
			override def mouseClicked(e: MouseEvent): Unit = {
				fun(e);
			}
		}
	}
	
}